package ch.ethz.fcl.metrobuzz.controller.gui.twl;

import java.io.IOException;
import java.net.URL;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.util.ResourceLoader;

import ch.ethz.fcl.metrobuzz.controller.MBController;
import ch.ethz.fcl.metrobuzz.controller.gui.twl.frames.TimeControlFrame;
import ch.ethz.fcl.metrobuzz.controller.gui.twl.frames.ToggleFrame;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer;
import de.matthiasmann.twl.theme.ThemeManager;

public class MBTWLGUI {
	private MBController control;
	private GUI gui;
	private LWJGLRenderer renderer = null;
	private RootPane root;
	private TimeControlFrame timeFrame;
	private ThemeManager themeManager = null;

	public MBTWLGUI(MBController control) {
		this.control = control;

		root = new RootPane(control);

		init();
	}

	private void loadTheme() {
		try {
			renderer = new LWJGLRenderer();
		} catch (LWJGLException e) {
			e.printStackTrace();
		}
		renderer.setUseSWMouseCursors(true);

		URL url = null;

		try {
			url = ResourceLoader.getResource("twl/simple_demo.xml");
		} catch (RuntimeException re) {
			url = ResourceLoader.getResource("res/twl/simple_demo.xml");
		}
		try {
			themeManager = ThemeManager.createThemeManager(url, renderer);
			GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void init() {
		loadTheme();

		timeFrame = new TimeControlFrame(control);
		root.addFrame(timeFrame);

		root.addButton("Time", new ToggleFrame(timeFrame), timeFrame);

		// InformationFrame infoFrame = new InformationFrame(control);
		// root.addFrame(infoFrame);
		// root.addButton("Help", new ToggleFrame(infoFrame), infoFrame);

		TWLMouseInputHandler inputHandler = new TWLMouseInputHandler(control,
				timeFrame);

		gui = new GUI(root, renderer, inputHandler);

		gui.applyTheme(themeManager);

		root.setSize(MBViewer.getWidth(), MBViewer.getHeight());

		root.layout();
	}

	public MBController getController() {
		return control;
	}

	public void reset() {
		root = new RootPane(control);
	}

	public void update() {
		if (gui != null) {
			((TWLMouseInputHandler) gui.getInput()).handleMouse(control
					.getMouseListener().getLeftMouse());

			gui.update();
		}
	}

	public TimeControlFrame getTimeControl() {
		return timeFrame;
	}

	public GUI getGUI() {
		return gui;
	}

	public LWJGLRenderer getRenderer() {
		return renderer;
	}
}
